package com.store.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.store.dto.EmployeeCreateRequest;
import com.store.dto.EmployeeQueryRequest;
import com.store.dto.EmployeeUpdateRequest;
import com.store.entity.User;
import com.store.mapper.OrderMapper;
import com.store.mapper.UserMapper;
import com.store.vo.EmployeeVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 员工服务类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class EmployeeService {
    
    private final UserMapper userMapper;
    private final OrderMapper orderMapper;
    
    /**
     * 创建员工
     */
    @Transactional(rollbackFor = Exception.class)
    public Long createEmployee(EmployeeCreateRequest request) {
        // 检查用户名是否已存在
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, request.getUsername());
        User existingUser = userMapper.selectOne(queryWrapper);
        if (existingUser != null) {
            throw new RuntimeException("用户名已存在");
        }
        
        // 检查手机号是否已存在
        LambdaQueryWrapper<User> phoneWrapper = new LambdaQueryWrapper<>();
        phoneWrapper.eq(User::getPhone, request.getPhone());
        User existingPhone = userMapper.selectOne(phoneWrapper);
        if (existingPhone != null) {
            throw new RuntimeException("手机号已被使用");
        }
        
        // 创建员工
        User employee = new User();
        employee.setUsername(request.getUsername());
        employee.setPassword(request.getPassword()); // 明文存储密码
        employee.setName(request.getName());
        employee.setPhone(request.getPhone());
        employee.setEmail(request.getEmail());
        employee.setAddress(request.getAddress());
        employee.setRole("employee");
        employee.setStatus(1); // 默认启用
        
        userMapper.insert(employee);
        
        log.info("创建员工成功，ID：{}，用户名：{}", employee.getId(), employee.getUsername());
        
        return employee.getId();
    }
    
    /**
     * 更新员工信息
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateEmployee(Long employeeId, EmployeeUpdateRequest request) {
        User employee = userMapper.selectById(employeeId);
        if (employee == null) {
            throw new RuntimeException("员工不存在");
        }
        if (!"employee".equals(employee.getRole())) {
            throw new RuntimeException("该用户不是员工");
        }
        
        // 检查手机号是否被其他用户使用
        if (request.getPhone() != null && !request.getPhone().equals(employee.getPhone())) {
            LambdaQueryWrapper<User> phoneWrapper = new LambdaQueryWrapper<>();
            phoneWrapper.eq(User::getPhone, request.getPhone());
            phoneWrapper.ne(User::getId, employeeId);
            User existingPhone = userMapper.selectOne(phoneWrapper);
            if (existingPhone != null) {
                throw new RuntimeException("手机号已被使用");
            }
        }
        
        // 更新信息
        if (request.getName() != null) {
            employee.setName(request.getName());
        }
        if (request.getPhone() != null) {
            employee.setPhone(request.getPhone());
        }
        if (request.getEmail() != null) {
            employee.setEmail(request.getEmail());
        }
        if (request.getAddress() != null) {
            employee.setAddress(request.getAddress());
        }
        if (request.getStatus() != null) {
            employee.setStatus(request.getStatus());
        }
        
        userMapper.updateById(employee);
        
        log.info("更新员工信息成功，ID：{}", employeeId);
    }
    
    /**
     * 删除员工
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteEmployee(Long employeeId) {
        User employee = userMapper.selectById(employeeId);
        if (employee == null) {
            throw new RuntimeException("员工不存在");
        }
        if (!"employee".equals(employee.getRole())) {
            throw new RuntimeException("该用户不是员工");
        }
        
        // 禁用员工而不是直接删除
        employee.setStatus(0);
        userMapper.updateById(employee);
        
        log.info("删除（禁用）员工成功，ID：{}", employeeId);
    }
    
    /**
     * 获取员工详情
     */
    public EmployeeVO getEmployeeDetail(Long employeeId) {
        User employee = userMapper.selectById(employeeId);
        if (employee == null) {
            throw new RuntimeException("员工不存在");
        }
        if (!"employee".equals(employee.getRole())) {
            throw new RuntimeException("该用户不是员工");
        }
        
        return convertToVO(employee);
    }
    
    /**
     * 查询员工列表（分页）
     */
    public IPage<EmployeeVO> getEmployeeList(int page, int pageSize, EmployeeQueryRequest queryRequest) {
        Page<User> pageParam = new Page<>(page, pageSize);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        
        // 只查询员工
        queryWrapper.eq(User::getRole, "employee");
        
        // 关键词搜索（用户名或姓名）
        if (queryRequest != null && queryRequest.getKeyword() != null && !queryRequest.getKeyword().trim().isEmpty()) {
            String keyword = queryRequest.getKeyword().trim();
            queryWrapper.and(wrapper -> 
                wrapper.like(User::getUsername, keyword)
                    .or()
                    .like(User::getName, keyword)
            );
        }
        
        // 状态筛选
        if (queryRequest != null && queryRequest.getStatus() != null) {
            queryWrapper.eq(User::getStatus, queryRequest.getStatus());
        }
        
        // 手机号筛选
        if (queryRequest != null && queryRequest.getPhone() != null && !queryRequest.getPhone().trim().isEmpty()) {
            queryWrapper.like(User::getPhone, queryRequest.getPhone().trim());
        }
        
        queryWrapper.orderByDesc(User::getCreateTime);
        
        IPage<User> employeePage = userMapper.selectPage(pageParam, queryWrapper);
        
        // 转换为VO
        IPage<EmployeeVO> voPage = employeePage.convert(this::convertToVO);
        
        return voPage;
    }
    
    /**
     * 获取所有员工列表（不分页）
     */
    public List<EmployeeVO> getAllEmployees() {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getRole, "employee");
        queryWrapper.eq(User::getStatus, 1); // 只查询启用的员工
        queryWrapper.orderByDesc(User::getCreateTime);
        
        List<User> employees = userMapper.selectList(queryWrapper);
        return employees.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }
    
    /**
     * 启用/禁用员工
     */
    @Transactional(rollbackFor = Exception.class)
    public void toggleEmployeeStatus(Long employeeId) {
        User employee = userMapper.selectById(employeeId);
        if (employee == null) {
            throw new RuntimeException("员工不存在");
        }
        if (!"employee".equals(employee.getRole())) {
            throw new RuntimeException("该用户不是员工");
        }
        
        // 切换状态
        employee.setStatus(employee.getStatus() == 1 ? 0 : 1);
        userMapper.updateById(employee);
        
        log.info("切换员工状态成功，ID：{}，新状态：{}", employeeId, employee.getStatus());
    }
    
    /**
     * 重置员工密码
     */
    @Transactional(rollbackFor = Exception.class)
    public void resetPassword(Long employeeId, String newPassword) {
        User employee = userMapper.selectById(employeeId);
        if (employee == null) {
            throw new RuntimeException("员工不存在");
        }
        if (!"employee".equals(employee.getRole())) {
            throw new RuntimeException("该用户不是员工");
        }
        
        employee.setPassword(newPassword); // 明文存储密码
        userMapper.updateById(employee);
        
        log.info("重置员工密码成功，ID：{}", employeeId);
    }
    
    /**
     * 获取员工统计信息
     */
    public EmployeeVO getEmployeeStatistics(Long employeeId) {
        EmployeeVO vo = getEmployeeDetail(employeeId);
        
        // 这里可以添加更多统计信息，比如：
        // - 处理的订单数
        // - 销售总额
        // - 退货处理数量等
        // 暂时返回基本信息
        
        return vo;
    }
    
    /**
     * 转换为VO
     */
    private EmployeeVO convertToVO(User user) {
        EmployeeVO vo = new EmployeeVO();
        vo.setId(user.getId());
        vo.setUsername(user.getUsername());
        vo.setName(user.getName());
        vo.setPhone(user.getPhone());
        vo.setEmail(user.getEmail());
        vo.setAvatar(user.getAvatar());
        vo.setRole(user.getRole());
        vo.setStatus(user.getStatus());
        vo.setAddress(user.getAddress());
        vo.setCreateTime(user.getCreateTime());
        vo.setUpdateTime(user.getUpdateTime());
        
        // 可以在这里添加统计信息
        // 例如：查询该员工处理的订单数量和销售额
        
        return vo;
    }
}
